const ErrCode = require('../utils/errCode');
const Status = require('../utils/status');
const { v4: uuidv4 } = require('uuid');

module.exports = class extends think.Controller {
    /**
     * @description 注册功能
     * @param {string} nickname 用户名
     * @param {string} account 用户账号
     * @param {string} password 用户密码
     * @returns {object} 响应信息
     */
    async registerAction() {
        const data = {...this.post(), power: 2 };
        let vaildUser = await this.model('user').where({ accunt: data.accunt }).find();
        const isNew = JSON.stringify(vaildUser) === '{}';
        if (isNew) {
            const status = await this.model('user').add({...data })
            return status > 0 ? this.success(status, Status.REGISTER_SUCCESS) : this.fail(ErrCode.REGISTER_FAIL.code, ErrCode.REGISTER_FAIL.msg);
        } else {
            return this.fail(ErrCode.USER_IS_EXIST.code, ErrCode.USER_IS_EXIST.msg);
        }
    }

    /**
     * @description 登录功能
     * @param {string} account 用户账号
     * @param {string} password 用户密码
     * @returns {userInfo} 响应信息
     */
    async loginAction() {
        const data = this.post();
        let password = await this.model('user').where({ accunt: data.accunt }).getField('password', true);
        if (password === data.password) {
            let userInfo = await this.model('user').where({...data }).find();
            let token = uuidv4();
            this.cache(token, userInfo); // thinkJS 的缓存
            return this.success({ token, nickname: userInfo.nickname }, Status.LOGIN_SUCCESS);
        } else {
            return this.fail(ErrCode.USER_IS_NOT_EXIST.code, ErrCode.USER_IS_NOT_EXIST.msg);
        }
    }

    async loginoutAction() {
        const data = this.post();
        const status = await this.cache(data.token, null);
        return this.success(undefined, Status.LOGIN_OUT_SUCCESS);
    }
};